import paramiko
import time


client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('172.23.1.20', port=22, username='zhang', password='*')
remote = client.invoke_shell()
remote.send('enable\n')
remote.send('iflyun\n')
time.sleep(1)
# print(remote.recv(1000).decode('utf-8'))
# time.sleep(1)


def command(cmd):
    remote.send(cmd + '\n')
    time.sleep(1)
    byte_buffer = b''
    while True:
        _buffer = remote.recv(2000)
        byte_buffer += _buffer
        str_buffer = _buffer.decode('utf-8')

        if '--More--' in str_buffer:        # 执行空格将继续接收数据。
            remote.send(' ')
            time.sleep(1)
        elif str_buffer.endswith('>') or str_buffer.endswith('#'):      # 缓冲区数据结尾是>或#说明命令已经结束。
            break

    return byte_buffer


def command2(cmd):
    remote.send(cmd + '\n')
    time.sleep(1)
    lines = []
    # while True:
    buffer = remote.recv(2000)

    while True:
        line = ''
        for b in buffer:
            if b in [10, 13]:
                if line != '':
                    lines.append(line)
                    line = ''
                continue
            line += chr(b)
        lines.append(line)
        if '--More--' in line:
            remote.send(' ')
            time.sleep(1)
        elif line.endswith('>') or line.endswith('#'):      # 缓冲区数据结尾是>或#说明命令已经结束。
            break

    print(lines)


c = command('show cpu')
print(c)
client.close()



